﻿using Coldairarrow.Entity.BackStage.Platform;
using Coldairarrow.Util;
using Coldairarrow.Util.DTO;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.BackStage.Platform
{
    public class Base_PlatformBusiness : BaseBusiness<Base_Platform>, IBase_PlatformBusiness, ITransientDependency
    {
        public Base_PlatformBusiness(IDbAccessor repository)
            : base(repository)
        {
        }

        #region 外部接口

        public async Task<PageResult<Base_Platform>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_Platform>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_Platform, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Base_Platform> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(Base_Platform data)
        {
            var aCount = GetIQueryable().Where(m => m.Id.Equals(data.Name) || m.Sort.Equals(data.Sort)).Count();
            if (aCount > 0)
            {
                throw new BusException("平台名称和编号不能重复，新增失败！");
            }
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(Base_Platform data)
        {
            var aCount = GetIQueryable().Where(m => !m.Id.Equals(data.Id) &&( m.Name.Equals(data.Name) || m.Sort.Equals(data.Sort))).Count();
            if (aCount > 0)
            {
                throw new BusException("平台名称和编号不能重复，新增失败！");
            }
            await UpdateAsync(data);
        }

        /// <summary>
        /// 后台——获取平台下拉列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<SelectDTO>> GetPlatformListAsync()
        {
            var list = await GetIQueryable().OrderBy(m => m.Sort).Select(x => new SelectDTO { Text = x.Name, Val =  x.Sort.ToString() }).ToListAsync();

            return list;
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}